package com.dup.jxlh.admin.validator;

import com.dup.jxlh.admin.entities.model.ChapterApply;
import com.dup.jxlh.admin.service.ChapterApplyService;
import com.dup.jxlh.admin.service.OwnValidatorService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigInteger;

public class ChapterApplyIdValidator implements ConstraintValidator<ChapterApplyId, BigInteger> {
    @Autowired
    private ChapterApplyService chapterApplyService;

    @Autowired
    private OwnValidatorService ownValidatorService;

    private boolean required = false;

    @Override
    public void initialize(ChapterApplyId constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(BigInteger s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null) {
            return !required;
        } else {
            ChapterApply chapterApply = chapterApplyService.getChapterApply(s);
            return ownValidatorService.byLevelValidator(chapterApply.getCompanyId(),
                    chapterApply.getDepartmentId(), chapterApply.getApplyId(), chapterApply.getCheckId());
        }
    }
}